import 'package:just_audio/just_audio.dart';
import 'package:vibration/vibration.dart';
import 'package:xindong/common/xindong_storage.dart';
import 'package:xindong/res/assets_res.dart';
import 'package:xindong/routes/call/controller/xindong_call_controller.dart';
import 'package:xindong/routes/tab_chats/controller/xindong_liaotian_vm.dart';

/// 声音震动管理
class XinDongShengYinZhenDongSingleton {
  final _audioPlayer = AudioPlayer();
  final kStorageKeyVoice = "voice";
  final kStorageKeyVibrate = "vibrate";
  bool enableVoice = true;
  bool enableVibrate = true;
  bool _isPlaying = true;
  bool? _hasVibrator; // 设备是否具有振动功能

  onInit() {
    enableVoice = XinDongStorage.instance.getBool(kStorageKeyVoice, defValue: true)!;
    enableVibrate = XinDongStorage.instance.getBool(kStorageKeyVibrate, defValue: true)!;
  }

  Future<bool>? changeEnableVoice() {
    enableVoice = !enableVoice;
    return XinDongStorage.instance.saveBool(kStorageKeyVoice, enableVoice);
  }

  Future<bool>? changeEnableVibrate() {
    enableVibrate = !enableVibrate;
    return XinDongStorage.instance.saveBool(kStorageKeyVibrate, enableVibrate);
  }

  void playVoiceAndVibrate() async {
    if (XinDongCallController.to.status != XinDongCallStatus.none && XinDongLiaoTianVM.to.currentConversationID != null)
      return;

    // 播放音频
    Future audioPlay() async {
      if (enableVoice) {
        await _audioPlayer.setAsset(AssetsRes.MESSAGE_TISHI);
        await _audioPlayer.play();
      }
      return Future.value();
    }

    // 触发震动
    Future vibrationAlert() async {
      // 检查目标设备是否具有振动功能
      if (enableVibrate) {
        _hasVibrator ??= await Vibration.hasVibrator();
        await Vibration.vibrate();
      }
      return Future.value();
    }

    if (_isPlaying) return;
    _isPlaying = true;
    // 并行异步等待
    await Future.wait([audioPlay(), vibrationAlert()]);

    // 设置一个延时，防止在短时间内重复触发
    Future.delayed(const Duration(milliseconds: 1000)).whenComplete(() {
      _isPlaying = false;
    });
  }

  // 停止
  Future<void> stop() async {
    return _audioPlayer.stop();
  }

  // 强制播放
  Future<void> forcePlay() async {
    await Vibration.vibrate();
  }

  // 暂停5秒才显示下一次
  void suspend() {
    Future.delayed(const Duration(seconds: 6), () {
      _isPlaying = false;
    });
  }

  /// ======== 单例
  // 工厂方法构造函数
  factory XinDongShengYinZhenDongSingleton() => _getInstance();

  // instance的getter方法，singletonManager.instance获取对象
  static XinDongShengYinZhenDongSingleton get instance => _getInstance();

  // 静态变量_instance，存储唯一对象
  static XinDongShengYinZhenDongSingleton? _instance;

  // 获取对象
  static XinDongShengYinZhenDongSingleton _getInstance() {
    _instance ??= XinDongShengYinZhenDongSingleton._internal();
    return _instance!;
  }

  // 私有的自定义命名式构造方法，通过它实现一个类;
  // 子类不能继承internal
  // 不是关键字，可定义其他名字
  XinDongShengYinZhenDongSingleton._internal() {
    //初始化(设置一些默认的)...
    onInit();
  }
}
